<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Goods;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use App\Models\Manufacturer;

class GoodsController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Goods(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('goods_name');
            $grid->column('manufacturer_id')->display(function($Id) {
                return Manufacturer::find($Id)->manufacturer_name;
            });
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Make a show builder.获取详情页面数据
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, \App\Models\Goods::find($id), function (Show $show) {
            $show->field('id');
            $show->field('goods_name');
            // 显示关联数据
//            $show->manufacturer('所属工厂', function (Show\Relation $relation) {
//                $relation->field('manufacturer_name');
//            });
            $show->field('manufacturer_id')->as(function($manufacturer_id){
                return Manufacturer::find($manufacturer_id)->manufacturer_name;
            });
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Goods(), function (Form $form) {
            $form->display('id');
            $form->text('goods_name');
            $form->select('manufacturer_id', '工厂名称')->options(Manufacturer::pluck('manufacturer_name','id')->toArray());
            $form->display('created_at');
            $form->display('updated_at');
        });
    }
}
